package com.edu.dao.impl;

import com.edu.beans.Home;
import com.edu.dao.HomeDao;
import com.edu.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class HomeDaoImpl implements HomeDao {

    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());

    @Override
    public int addHome(Home home) {
        try {
            return qr.update("insert into tb_home values(null,?,?,?,?,?,?,now(),now())",
                    home.getNum(), home.getH_type(), home.getPrice(), home.getState(), home.getImg(), home.getText());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteHomeById(int id) {
        try {
            return qr.update("delete from tb_home where id = ?", id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateHome(Home home) {
        try {
            return qr.update("update tb_home set num = ?, h_type = ?, price = ?, state = ?, img = ?, text = ?,updatetime=now() where id = ?",
                    home.getNum(), home.getH_type(), home.getPrice(), home.getState(), home.getImg(), home.getText(), home.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Home getHomeById(int id) {
        try {
            return qr.query("SELECT * FROM tb_home WHERE id = ?", new BeanHandler<>(Home.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Home> getAllHomeByNum(String num) {
        try {
            if (num == null || num.isEmpty()) {
                return qr.query("SELECT * FROM tb_home order by id desc ", new BeanListHandler<>(Home.class));

            } else {
                return qr.query("select * from tb_home where num = ?", new BeanListHandler<>(Home.class), Integer.parseInt(num));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Home> getHomeByState(String state) {
        try {
            return qr.query("SELECT * FROM tb_home WHERE state = ?", new BeanListHandler<>(Home.class), state);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
